<template>
  <div class="box">
    <div class="search">
      <SearchForm :formInputs="state.formInputs" @submit="search" />
    </div>
    <div class="table">
      <p :style="{ textAlign: 'right', marginBottom: '5px' }">
        <a-button @click="action('add')" type="primary" link
          ><template #icon>
            <PlusOutlined />
          </template>
          添加</a-button
        >
      </p>
      <a-table
        size="middle"
        :data-source="state.tableData"
        :columns="[
          {
            title: '用户名',
            dataIndex: 'userName',
            key: 'userName',
          },
          {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
          },
          {
            title: '角色',
            key: 'role',
            dataIndex: 'role',
          },
          {
            title: '电话',
            key: 'tel',
            dataIndex: 'tel',
          },
          {
            title: '部门',
            key: 'department',
            dataIndex: 'department',
          },
          {
            title: '操作',
            key: 'action',
            width: 120,
            align: 'center',
          },
        ]"
        :pagination="state.pager"
        @change="handleTableChange"
        stripe
        bordered
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a-space :size="10" spacer="|">
              <DeleteBtn
                title="确认删除?"
                label="删除"
                @onDelete="action('remove', record)"
              />
              <a-button type="link" @click="action('edit', record)" link
                ><template #icon>
                  <EditOutlined />
                </template>
                编辑</a-button
              >
            </a-space>
          </template>
          <template v-else-if="column.key === 'department'">
            {{ record.department }}
          </template>
        </template>
      </a-table>
    </div>
    <FormModal
      :formConfig="state.formConfig"
      @submit="submit"
      ref="dialogRef"
    />
  </div>
</template>

<script setup>
import { onBeforeMount, getCurrentInstance, reactive, ref } from "vue";
import _ from "lodash";
import FormModal from "@/components/FormModal.vue";
import SearchForm from "@/components/SearchForm.vue";
import DeleteBtn from "@/components/DeleteBtn.vue";
import { useMainStore } from "@/store/index.js";
import { menus } from "@/utils/menus.js";

const mainStore = useMainStore();
const { user } = mainStore;
//const menusFiltered = menus.filter(menu => menu.label !== "信息管理");
//console.log('menus',menusFiltered)
const { proxy } = getCurrentInstance();
const state = reactive({
  formInputs: [{ label: "名称", type: "input", name: "name" }],
  formConfig: {
    title: "用户信息提交",
    items: [
      {
        type: "hidden",
        name: "id",
      },
      {
        label: "用户名",
        type: "input",
        name: "userName",
        span: 12,
        rules: [
          {
            required: true,
            message: "请输入用户名",
          },
          {
            min: 5,
            max: 35,
            message: "长度必须在5-35",
          },
          {
            pattern: new RegExp("^\\w+$", "g"),
            message: "只能输入字母,数字,下划线",
          },
        ],
      },
      {
        label: "密码",
        type: "password",
        name: "password",
        span: 12,
        rules: [
          {
            required: true,
            message: "请输入密码",
          },
          {
            min: 5,
            max: 35,
            message: "长度必须在5-35",
          },
        ],
      },
      {
        label: "姓名",
        type: "input",
        name: "name",
        span: 12,
        rules: [
          {
            required: true,
            message: "请输入名称",
          },
          { max: 50, message: "超过50字符" },
        ],
      },
      {
        label: "角色",
        type: "radio",
        name: "role",
        span: 12,
        options: [
          { label: "管理员", value: "admin" },
          { label: "用户", value: "user" },
        ],
        rules: [
          {
            required: true,
            message: "请选择角色",
          },
        ],
      },
      {
        label: "电话",
        type: "input",
        name: "tel",
        span: 12,
        rules: [
          {
            pattern: /^1[3|4|5|7|8|9]\d{9}$/,
            message: "请输入正确的手机号",
          },
        ],
      },
      {
        label: "部门",
        type: "input",
        name: "department",
        span: 12,
        rules: [
          {
            max: 150,
            message: "长度必须在150以内",
          },
        ],
      },
      {
        label: "菜单",
        type: "treeSelect",
        name: "workFlows",
        options: menus,
        multiple: true,
        rules: [
          {
            required: true,
            message: "请选择菜单",
          },
        ],
      },
    ],
  },
  searchObj: { name: null },
  tableData: [],
  pager: {
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: false,
    size: "normal",
  },
});
const dialogRef = ref();

const getList = (page) => {
  const name = state.searchObj.name;
  proxy.$axios
    .get("/user/list", {
      params: { pageNumber: page, pageSize: state.pager.pageSize, name },
    })
    .then(({ success, data }) => {
      if (success) {
        const list = data.content;
        state.tableData = list;
        state.pager.total = data.totalElements;
        state.pager.current = page;
      }
    });
};

const handleTableChange = ({ current }) => {
  getList(current);
};

const search = (value) => {
  state.searchObj.name = value.name;
  getList(1);
};

const submit = (value) => {
  let method = "post";
  let url = "/user";
  if (value.id) {
    method = "put";
    url += `/${value.id}`;
  }
  proxy.$axios({ method, data: value, url }).then(({ success, data }) => {
    if (success) {
      // 修改当前用户，则更新用户数据
      if (user.id === data.id) {
        mainStore.setUser(data);
      }
      dialogRef.value.cancel();
      proxy.$message.success("提交成功");
      getList(1);
    }
  });
};

const action = (type, record) => {
  const field = _.find(state.formConfig.items, { name: "userName" });
  if (type === "add") {
    field.disabled = false;
    dialogRef.value.handleOpenForm({});
  } else if (type === "edit") {
    field.disabled = true;
    dialogRef.value.handleOpenForm({ ...record });
  } else if (type === "remove") {
    proxy.$axios.delete(`/user/${record.id}`).then(({ success }) => {
      if (success) {
        getList(1);
      }
    });
  }
};

//生命周期钩子函数
onBeforeMount(() => {
  getList(1);
});
</script>

<style lang="less" scoped>
.box {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 10px;

  .search {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px;
  }

  .table {
    flex: 1;
    padding: 2px;
    overflow-y: auto;
  }
}
</style>
